package com.jdjc.wx.handler;

import com.jdjc.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 接收用户文本消息
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler {

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX="loginCode";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WeChatMsgTypeEnum getMsgType() {
        return WeChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info("接收到用户文本消息");
        String content = msgMap.get("Content");
        log.info("content:{}", content);
        if (!KEY_WORD.equals(content)) {
            return "";
        }

        String fromUserName = msgMap.get("FromUserName");
        String toUserName = msgMap.get("ToUserName");

        Random random = new Random();
        int num=random.nextInt(1000);
        String numContent="您当前验证码为："+num+"，5分钟内有效";

        //将验证码存入redis
        //生成一个唯一的键，以便在 Redis 数据库中存储或检索数据。这里以loginCOde_验证码为键
        String numKey = redisUtil.buildKey(LOGIN_PREFIX,String.valueOf(num));
        //缓存numkey，过期时间1分钟，value值为微信用户的唯一标识openid（fromUserName）
        redisUtil.setNx(numKey,fromUserName,5L, TimeUnit.MINUTES);

        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";

        return replyContent;

    }
}
